#!/usr/bin/env python
# coding: utf-8
#sys._getframe().f_back.f_code.co_name

# debugInfo("checknow ",sys._getframe().f_code.co_name)
# form inspect import *
import sys
from engine.common import *
from task.tasklist import *
import datetime
class engine:
    """HANDSET"""
    nvli = ""
    aTaskList = ''
    currentTaskFileName= ""
    def __init__(self):
        self.DEBUG = True
        self.Sno = ''
        self.ip = ''
        self.type = ''
        self.status = ""
        self.device_id = self.Sno
        self.test = 0
        debugInfo("init")
        debugInfo("__init__",sys._getframe().f_back.f_code.co_name)
    def setEngineSno(self,sno):
        self.Sno = sno

    def handle_msg_all(self, msg):
        """
        处理所有消息，请子类化后覆盖此函数
        msg:
            msg_id  ->  消息id
            msg_type_id  ->  消息类型id
            user  ->  发送消息的账号id
            content  ->  消息内容
        :param msg: 收到的消息
        """
        #debugInfo("handle_msg_all----------------------")
        pass
    def getIniFile(self,path):
        ret = 'null'
        file_list = os.listdir(path)
        for file in file_list:
            if '.ini' in file:
                ret = file
                break
        return ret
    def findTask(self):
        if not os.path.exists("./shouji/"+self.type+"/task/"+self.Sno+"/"):
            os.mkdir("./shouji/"+self.type+"/task/"+self.Sno+"/")
            os.mkdir("./shouji/"+self.type+"/task/"+self.Sno+"/runned")
            os.mkdir("./shouji/"+self.type+"/task/"+self.Sno+"/running")
        ret  = self.getIniFile("./shouji/"+self.type+"/task/"+self.Sno+"/");
        self.currentTaskFileName = ret
        return ret

    def handle_msg(self, r):
        #debugInfo("handle_msg")
        #是否有task 在run ，task id是啥？
        #如果没有在run的。。。。。
        #read taskpool get a tasklist for parser
        #如果没有得到tasklist goon
        #如果有 那么初始化tasklist  set current task id and task status 0
        #如果有task 在run呢？
        #当前tasklist status 是结束吗，是结束就结束这个tasklist id 状态清理下
        #如果不是结束状态那么 执行一步，
        #find the watch dir exist task or not


        if isinstance(self.aTaskList,str) and len(self.aTaskList) == 0:
            if   'ini' in self.findTask():
                print(self.type)
                print(self.Sno)
                 #time.sleep(100)
                 #find a task then mv it to readpath ,and parser it now
                cmd = "mv "+os.getcwd()+"/shouji/"+self.type+"/task/"+self.Sno+"/"+self.currentTaskFileName+" "+os.getcwd()+"/shouji/"+self.type+"/task/"+self.Sno+"/running/"+self.currentTaskFileName
                os.system(cmd)
                 #init aTaskList for run
                self.aTaskList = taskList("./shouji/"+self.type+"/task/"+self.Sno+"/running/"+self.currentTaskFileName)
                #任务列表初始化完成后 检查手机是否链接 检查屏幕是否亮 不亮 点亮 并回到待机，灭的情况 点亮屏幕解锁
                isHandsetConnected("called at the start a tasklist inited checking")
                isReadyToRunTask()


        self.handle_msg_all(r)

    def schedule(self,r):
        """
        做任务型事情的函数，如果需要，可以在子类中覆盖此函数
        此函数在处理消息的间隙被调用，请不要长时间阻塞此函数
        """
        if self.aTaskList !='':
            if self.aTaskList.currentPos == self.aTaskList.totalTaskItem:
                print("end of this task ")
            else:
                itemStatusRet,itemStatus = self.aTaskList.itemList[self.aTaskList.currentPos].itemStatusUpdate(self.nvli.screenNow)
                #time.sleep(0.2)
                if "done" in itemStatus:
                    self.aTaskList.itemList[self.aTaskList.currentPos].innerStatus = "ready"
                    self.aTaskList.currentPos = self.aTaskList.currentPos+1
                    if "None" not in itemStatusRet and itemStatusRet.isdigit():
                        if int(itemStatusRet) < self.aTaskList.totalTaskItem and int(itemStatusRet)>0:
                            self.aTaskList.currentPos = int(itemStatusRet) -1
                        else:
                            print("任务跳转情况结束："+itemStatusRet)
                            self.aTaskList.currentPos = self.aTaskList.totalTaskItem


                if self.aTaskList.currentPos == self.aTaskList.totalTaskItem:
                    print("end of this task ")
                    print("pls set the currentPos back 0,clear the task,mv it to runed task backup ")
                    self.aTaskList.emptyItem()
                    self.aTaskList.totalTaskItem = 0
                    del  self.aTaskList
                    cmd = "mv ./shouji/"+self.type+"/task/"+self.Sno+"/running/"+self.currentTaskFileName+" ./shouji/"+self.type+"/task/"+self.Sno+"/runned/"+self.currentTaskFileName
                    os.system(cmd)
                    isRunTaskComplete()
        else:
            print("there is no task ")
            if '.' in getHandsetSno():
                cmd = getAdbPath()+ "connect "+getHandsetSno()
                print(cmd )
                os.system(cmd)
            time.sleep(10)
        pass

    def proc_msg(self):
        r = ""
        pcount = 0
        while True:
            # starttime = datetime.datetime.now()
            # print("startTime="+str(starttime))
            if self.status == 'ready':
                debugInfo("ready to run" )
                self.status = "run"
                self.nvli.screenJustOne()
            else:
                #debugInfo("running")
                pass

            try:
                self.handle_msg(r)
                # watchValue = self.nvli.screenJustOne()
                # if pcount %1000==0:
                #     print("nojustone")
                #     #watchValue = self.nvli.screenJustOne()
                # else:
                #     print("ignore")
                #
                # pcount = pcount +1
                # print(pcount)
                # if pcount >65535:
                #     pcount = 0
                #
                # #time.sleep(1)
            except:
                time.sleep(1)
                print("user stop now then   exit-------------------------")
                sys.exit(1)
                pass
            self.schedule(r)
            # endTime = datetime.datetime.now()
            # print("endTime="+str(endTime))
    def run(self):
        try:
            self.status = 'ready'
            self.proc_msg()
        except Exception as err:
            if 1:#printDebug
                import sys
                info = sys.exc_info()[2].tb_frame.f_back
                temp = "filename:{}\nlines:{}\tfunc:{}\terror:{}"
                print(temp.format(info.f_code.co_filename,info.f_lineno,0,repr(err)))
            self.status = 'out'
    def runx(self):
        self.status = 'ready'
        self.proc_msg()




    def __init__(self):
        pass
    def __init__(self,type,sno):
        self.device_id = sno
        self.Sno =sno
        self.type = type
        self.test = 0
        self.nvli = PERSON(self.type,self.Sno)
        pass

